export default class UrlUtils {
  static parseUrlParams(url: string): { [key: string]: string } | null {
    if (url == null) return null
    const params: { [key: string]: string } = {}
    const queryString = url.split('?')[1]

    if (queryString) {
      const pairs = queryString.split('&')

      pairs.forEach((pair) => {
        const [key, value] = pair.split('=')
        params[key] = decodeURIComponent(value)
      })
    }
    return params
  }
  static encodeParams(params: Record<string, any>): string {
    const strArray: string[] = []

    for (const key in params) {
      if (Object.prototype.hasOwnProperty.call(params, key)) {
        let value = params[key]

        // Convert value to string
        if (typeof value === 'object') {
          value = JSON.stringify(value)
        }

        // Encode both key and value
        const encodedKey = encodeURIComponent(key)
        const encodedValue = encodeURIComponent(value)

        // Push into the array
        strArray.push(encodedKey + '=' + encodedValue)
      }
    }

    // Join all parameters with '&' and prepend with '?'
    return '?' + strArray.join('&')
  }
}
